import { createRouter, createWebHistory } from 'vue-router'
import { checkTokenValid } from '@/utils/auth';
import { message } from 'ant-design-vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
    },
    // 认证相关路由
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/auth/Login.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/auth/Register.vue'),
    },
    {
      path: '/course/learn/:courseId/:outlineId?',
      name: 'courseLearn',
      component: () => import('../views/course/CourseLearn.vue'),
    },
    // 个人中心路由（嵌套路由）
    {
      path: '/user',
      name: 'UserCenter',
      component: () => import('../views/user/UserCenter.vue'),
      children: [
        {
          path: 'teams',
          name: 'userTeams',
          component: () => import('../views/user/MyTeam.vue'), // TODO: 替换为我的战队
        },
        {
          path: 'posts',
          name: 'userPosts',
          component: () => import('../views/user/MyPosts.vue'), // TODO: 替换为审核帖子
        },
        {
          path: 'doc',
          name: 'userDoc',
          component: () => import('../views/user/MyDoc.vue'),
        },
        {
          path: 'notes',
          name: 'userNotes',
          component: () => import('../views/user/MyNotes.vue'),
        },
        {
          path: 'points',
          name: 'userPoints',
          component: () => import('../views/user/MyPoints.vue'),
        },
        {
          path: 'orders',
          name: 'userOrders',
          component: () => import('../views/user/MyOrders.vue'),
        },
        // 新增的用户题目的路由
         {
          path: 'questions',
          name: 'questions',
          component: () => import('../views/user/Myassignments.vue'),
        },
        // 新增我的审核
        {
          path: 'reviews',
          name: 'userReviews',
          component: () => import('../views/user/MyReviews.vue'),
        },
      ]
    },
    // 组队学习路由（嵌套路由）
    {
      path: '/teamLearning',
      name: 'teamLearning',
      component: () => import('../components/TeamLearning.vue'),
    },
    {
        path: '/teamLearningPlatform',
        name: 'teamLearningPlatform',
        component: () => import('../components/TeamLearningPlatform.vue'),
    },
    {
      path: '/myTeams',
      name: 'myTeams',
      component: () => import('../components/teamlearning/MyTeams.vue'),
    },
    // 管理端路由
    {
      path: '/admin',
      name: 'admin',
      component: () => import('../views/admin/AdminLayout.vue'),
      children: [
        {
          path: '',
          name: 'adminDashboard',
          component: () => import('../views/admin/Dashboard.vue'),
        },
        {
          path: 'permissions',
          name: 'adminPermissions',
          component: () => import('../views/admin/PermissionManagement.vue'),
        },

        {
          path: 'courses',
          name: 'adminCourses',
          component: () => import('../views/admin/CourseManagement.vue'),
        },
        {
          path: 'users',
          name: 'adminUsers',
          component: () => import('../views/admin/UserManagement.vue'),
        },
        {
          path: 'assignments',
          name: 'adminAssignments',
          component: () => import('../views/admin/AssignmentManagement.vue'),
        },
        {
          path: 'exams',
          name: 'adminExams',
          component: () => import('../views/admin/ExamManagement.vue'),
        },
        {
          path: 'orders',
          name: 'adminOrders',
          component: () => import('../views/admin/OrderManagement.vue'),
        },
        {
          path: 'settings',
          name: 'adminSettings',
          component: () => import('../views/admin/SystemSettings.vue'),
        },
        {
          path: 'videos',
          name: 'adminVideos',
          component: () => import('../views/admin/VideoManagement.vue'),
        },
        {
          path: 'task-management',
          name: 'task-management',
          component: () => import('../views/admin/AdminTaskManagement.vue'),
        },
      ],
    },
    // 战队订阅相关的界面路由
    {
    path: '/team',
    name: 'teamSubscribe',
    component: () => import('@/views/TeamSubscribe/TeamSubscribe.vue'),
    },
     // 发布文章的路由
    {
    path: '/addText',
    name: 'addText',
    component: () => import('@/views/addText/AddText.vue'),
    },
    //作业的路由
    {
    path: '/course/:videoId/assignment',
    name: 'Assignment',
    component: () => import('../components/course/AssignmentPage.vue'),
    },
    {
      path: '/ai-chat',
      name: 'aiChat',
      component: () => import('../views/AIAssistantLayout.vue'),
    },
    //ai生成问题的单独界面的路由
    {
  path: '/ai-generate',
  name: 'AiGenerate',
  component: () => import('@/components/questionCenter/AiGenerate.vue')
    },

    // 404页面 - 必须放在最后，捕获所有不存在的路径
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('../views/NotFound.vue'),
    },
  ],
})

// 路由守卫（保持不变）
router.beforeEach(async (to, from, next) => {
  // 1. 定义公开路由（不需要登录）
  const publicRoutes = ['/login', '/register', '/'];
  
  // 2. 如果是公开路由，直接放行 公开路由不校验 token
 if (publicRoutes.includes(to.path)) {
    return next();
  }

  // 3. 检查用户登录状态
  const userInfo = localStorage.getItem('userInfo');
  const token = localStorage.getItem('token');
  
if (!userInfo || !token) {
   message.warning('请先登录');
   return next(`/login`);
}

  try {
    // 情况2：有token但需要验证有效性
    const isValid = await checkTokenValid();
    
    if (!isValid) {
      throw new Error('Token无效或已过期');
    }
    
    next();
  } catch (error) {
    // 情况3：token验证失败
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    message.warning('会话已过期，请重新登录');
    next('/');
  }
});

export default router

